package jprofiler.thread;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Person {

    private Integer pId;
    private String pName;
    private Random random = new Random();
    // 计算器
    private static Object calculator = new Object();

    private Lock lock = new ReentrantLock();


    public Person() {
    }

    public Person(Integer pId, String pName) {
        this.pId = pId;
        this.pName = pName;
    }


    // 做某些事情
    public void doSomething() {
        // doDifferentThing();
        synchronized (calculator){
            this.sum2();
        }
        // doLockThing();
//         System.out.println("thingType=" + thingType + " sum=" + sum);
    }

    private void doLockThing() {
        try{
            lock.lock();
            this.sum2();
        }finally {
            lock.unlock();
        }
    }

    private void doDifferentThing() {
        int thingType = random.nextInt(3);
        int sum = 0;
        switch (thingType) {
            case 0: // 轻
                sum = this.sum0();
                break;

            case 1: // 中
                sum = this.sum1();
                break;

            case 2: // 重
                sum = this.sum2();
                break;

            default:
                break;
        }
    }

    // 轻活
    private int sum0() {
        int a = 1, b = 1;
        int sum = a + b;
        return sum;
    }

    // 中活
    private int sum1() {
        int sum = 0;
        for (int i = 0; i < 1000; i++) {
            sum += i;
            sum += i - sum;
        }
        return sum;
    }

    // 重活
    private int sum2() {
        int sum = 0;
        for (int i = 0; i < 100000; i++) {
            sum += (i % 10);
            sum += (sum % 10);
            sum += (sum % 10);
        }
        return sum;
    }

    public static void main(String[] args) {

        for (int i = 0; i < 6; i++) {
            final int num = i;
            new Thread() {
                @Override
                public void run() {
                    Thread.currentThread().setName("子线程_" + num);
                    while (true) {
                        int pid = 0;
                        // 不停的创建对象，并打印他的名字
                        Person person = new Person(pid, "person_" + pid);

                        // 做某些事情
                        person.doSomething();

                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

                ;
            }.start();

        }


    }
}
